'use client';

import { cn } from '@/lib/utils';
import { useCosClient } from '@/providers/cos-provider';
import { useQuery } from '@tanstack/react-query';
import Image, { type StaticImageData } from 'next/image';
import { useState } from 'react';
import { Skeleton } from '../ui/skeleton';

export default function QueryImage({
  imageKey,
  defaultImage,
  wrapperClassName,
  imgClassName,
}: {
  imageKey?: string | null;
  defaultImage?: StaticImageData;
  wrapperClassName?: string;
  imgClassName?: string;
}) {
  const cosClient = useCosClient();
  const { data: imageUrl, isLoading: isUrlLoading } = useQuery({
    queryKey: ['image', imageKey],
    queryFn: () => {
      if (cosClient && imageKey) return cosClient.getObjectUrl(imageKey, 900);
    },
    enabled: !!imageKey && !!cosClient,
    staleTime: 1000 * 900,
  });
  const [isLoading, setIsLoading] = useState(true);
  const loading = isUrlLoading || isLoading;

  return (
    <div
      className={cn(
        'relative w-full',
        { 'aspect-video': loading },
        wrapperClassName,
      )}
    >
      {loading && !!imageKey && (
        <Skeleton
          className={cn('w-full aspect-video absolute', wrapperClassName)}
        />
      )}
      {!imageKey && !!defaultImage && (
        <Image
          src={defaultImage}
          width={500}
          height={500}
          alt={imageKey ?? 'image'}
          className={cn('rounded', imgClassName)}
        />
      )}
      {!!imageKey && !!imageUrl && (
        <Image
          onLoad={() => setIsLoading(false)}
          src={imageUrl}
          width={500}
          height={500}
          alt={imageKey ?? 'image'}
          className={cn('rounded', imgClassName)}
        />
      )}
    </div>
  );
}
